function request(url, data, cb, ffn) {
  var app = getApp();
  if (url.indexOf('https') === -1 && url.indexOf('http') === -1) url = app.serverUrl + url

  wx.request({
    url,
    dataType: 'json',
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    data,
    success(res) {
      if (res.statusCode == 200) {
        if (res.data.header) {
          const code = res.data.header.code;
          if (code === 10000) {
            // 先登录
            doLoginOther(() => {
              // 赋值新的sessionID
              data.sessionID = wx.getStorageSync("USER_SESSIONID")
              if (data.hasOwnProperty("memberID")) {
                data.memberID = wx.getStorageSync("USER_MEMBERID")
              }
              // 登录完毕再次发送请求
              request(url, data, cb, ffn);
            }, (err) => {
              if (ffn) ffn(err)
            });
          } else {
            // 其他错误 true代表出错了
            if (cb) cb(res);
          }
        } else {
          if (cb) cb(res)
        }
      } else if (res.statusCode == 500) {
        wx.showToast({
          title: '网络连接超时，请稍后再试。',
          icon: 'none'
        })
        if (ffn) ffn(res)
      } else if (res.statusCode == 404) {
        wx.showToast({
          title: '网络连接超时，请待会再试。',
          icon: 'none'
        })
        if (ffn) ffn(res)
      } else {
        wx.showToast({
          title: '网络连接超时，请重试。',
          icon: 'none'
        })
        if (ffn) ffn(res)
      }
    },
    fail(err) {
      if (!data.hideErr) {
        var times = wx.getStorageSync("ERROR_TIMES")
        if (!times || times < 3) {
          times = times ? times : 1;
          request(url, data, cb, ffn)
          times++
          wx.setStorageSync("ERROR_TIMES", times)
        } else {
          wx.showToast({
            title: '网络较慢，请重试或刷新页面。',
            icon: 'none'
          })
          wx.setStorageSync("ERROR_TIMES", 0)
          if (ffn) ffn(err)

        }
      }
    }
  })
}

function doLoginOther(okWay, ffn) {
  // 设置状态为登陆中 
  wx.showLoading({
    title: '正在登陆中',
    mask: true
  })
  //调用登录接口
  wx.login({
    success(r) {
      var code = r.code; //登录凭证
      wx.setStorageSync("LOGIN_CODE", code)
      if (code) {
        var USER_DEFAULT = wx.getStorageSync("USER_DEFAULT");
        var openid = wx.getStorageSync('USER_OPENID');
        if (!USER_DEFAULT) {
          wx.getSetting({
            success: function (res) {
              if (res.authSetting['scope.userInfo'] !== true) {
                wx.navigateTo({
                  url: '/pages/loginIndex/loginIndex'
                })
                wx.hideLoading()
              } else {
                console.log('获取用户信息')
                wx.getUserProfile({
                  desc: '用于完善会员资料',
                  success: (res) => {
                    console.log(res)
                    if (res.userInfo != null) {
                      wx.setStorageSync("USER_DEFAULT", {
                        avatarUrl: res.userInfo.avatarUrl,
                        nickName: res.userInfo.nickName
                      })
                      utils.doLoginOther((data) => {
                        that.setData({
                          member: data
                        })
                      })
                    }
                  }
                })
                if (!openid) {
                  getOpenID(okWay, ffn)
                } else {
                  login(okWay, ffn);
                }
              }
            },
            fail() {
              wx.hideLoading()
              doLoginOther(okWay)
            }
          })
        } else if (!openid) {
          getOpenID(okWay, ffn)
        } else {
          login(okWay, ffn)
        }
      }
    },
    fail() {
      wx.hideLoading()
      doLoginOther(okWay)
    }
  });
}

function login(result, ffn, times) {
  var app = getApp();
  if (!times) {
    times = 0
  }
  var USER_DEFAULT = wx.getStorageSync("USER_DEFAULT");
  var data = {};
  data.name = USER_DEFAULT.nickName;
  data.code = wx.getStorageSync('USER_OPENID');
  data.appServerCode = app.publicNo;
  data.siteID = app.siteID;
  data.loginType = 2;
  data.avatarUrl = USER_DEFAULT.avatarUrl;
  var memberID = wx.getStorageSync('recommandID')
  if (memberID) {
    data.recommandID = memberID
  }

  request(app.serverUrl + 'appLogin.json', data, (res) => {
    wx.hideLoading()
    if (res.data.header.code == 0) {
      var data = res.data.body;
      wx.removeStorageSync('recommandID')
      wx.setStorageSync("USER_SESSIONID", data.sessionID)
      wx.setStorageSync("USER_MEMBERID", data.memberID)
      //获取用户信息
      request(app.serverUrl + 'getMemberInfo.json', data, (res) => {
        wx.setStorageSync("USER_MEMBER", res.data.body.data)
        result(res.data.body.data)
      }, err => {
        wx.showModal({
          title: '提示',
          content: '登录失败，请联系管理员',
        })
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '登录失败，' + res.data.body.msg,
      })
      if (ffn) ffn(res)
    }
  }, err => {
    wx.hideLoading();
    times++
    if (times >= 3) {
      wx.showToast({
        title: '您多次登录失败，请联系管理员。',
        icon: 'none'
      })
      if (ffn) ffn(err)
    } else {
      login(result, ffn, times)
    }

  })

}
// name-"列表名"  list-"列表"  data-"res.data.body.data" that-"that"
function ListPage(name, list, data, that) {
  if (data.currentPage > 1) {
    list = that.data[name]
  }
  var Page = name + "Page";

  list = list.concat(data.rows);
  that.setData({
    [name]: list,
    [Page + ".currentPage"]: data.currentPage,
    [Page + ".hasNextPage"]: data.hasNextPage,
    [Page + ".total"]: data.total,

    showAjaxLoad: false,
  })
  that.ReachBottomOne = false
}
//
function getOpenID(fun) {
  var app = getApp()
  var code = wx.getStorageSync("LOGIN_CODE")
  wx.showLoading({
    title: '获取系统参数',
  })
  request(app.serverUrl + "getWeiXinAppOpenId.json", {
    "publicNo": app.publicNo,
    "js_code": code
  }, res => {
    wx.hideLoading()
    var openid = res.data.body.openID;
    if (openid) {
      wx.setStorageSync('USER_OPENID', openid);
      var data = login(fun);
    } else {
      wx.showToast({
        title: '小程序状态异常，请在微信号反馈。',
        icon: 'none'
      })
      app.LOGIN = false
    }
  }, err => {
    wx.hideLoading()
    app.LOGIN = false
    if (ffn) ffn(err)
    // getOpenID(fun)
  })
}

// 分页
function FY(req, that, name) {
  var name = name + "Page";
  var Page = that.data[name];
  if (Page) {
    var currentPage = Page.currentPage;
    var pageNumber = Page.pageNumber;
    req.currentPage = currentPage ? currentPage : 1;
    req.pageNumber = pageNumber ? pageNumber : 10;
  } else {
    that.setData({
      [Page]: {}
    })
    req.currentPage = 1;
    req.pageNumber = 10;
  }

}
// 获取sessinID
function GS() {
  return {
    sessionID: wx.getStorageSync("USER_SESSIONID")
  }
}
// 提交附件图
function submitPicture(data) {
  var req = GS();
  req.objectID = data.objectID;
  req.objectDefineID = data.objectDefineID;
  req.memberID = data.memberID;
  req.fileType = data.fileType;
  req.showType = data.showType;
  req.objectName = data.objectName;
  for (var item of data.imageList) {
    req.imageUrl = item.url
    request('submitObjectPicture.json', req, res => {

    }, (err) => {

    })
  }
}
// 全局接口
function request1(q, u, n, rf) { // 接口类型  接口名称  justone  列表名称
  var app = getApp();
  var url = {};
  var s = q.indexOf("s") > -1;
  url.d = url.ds = app.dServerUrl; // 独立接口
  url.y = url.ys = app.serverUrl; // 一般接口
  url.w = url.ws = app.wServerUrl; // 微服务接口
  url.s = url.ss = app.sServerUrl; // 短接口
  q = url[q] ? url[q] : url.y;
  return function (data, that, fun, ffn) {
    var req = s ? GS() : {};
    for (var key in data) {
      if (data[key]) {
        req[key] = data[key];
      }
    }
    if (data.ListName) FY(req, that, data.ListName)
    var AjaxSend = request(q + u, req, res => {
      if (data.ListName) {
        if (res.data.header.code == 0) {
          var rbody = res.data.body.data;
          if (rf) rf(rbody)
          ListPage(data.ListName, [], rbody, that)
        }
      }
      if (fun) fun(res)
    }, err => {
      if (ffn) ffn(err)
    })
    var AjaxArray = that.data.AjaxArray ? that.data.AjaxArray : [];
    AjaxArray.push(AjaxSend)
    that.data.AjaxArray = AjaxArray
  }
}

/** 
 * new Date() ---> 转化为 年 月 日 时 分 秒
 * let date = new Date();
 * date: 传入参数日期 Date
 */
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/** 
 * 时间戳转化为年 月 日 时 分 秒 
 * number: 传入时间戳 
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
 */
function formatTimeTwo(number, format) {

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];

  var date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}

function addDate(date, days) {
  if (days == undefined || days == '') {
    days = 1;
  }
  var date = new Date(date);
  date.setDate(date.getDate() + days);
  var month = date.getMonth() + 1; //月份从0开始所以需要+1
  if (month < 10) {
    month = "0" + month
  }
  var day = date.getDate();
  if (day < 10) {
    day = "0" + day
  }
  return date.getFullYear() + '-' + month + '-' + day;
}

module.exports = {
  doLoginOther,
  request,
  FY,
  GS,
  submitPicture,
  request1,
  formatTime,
  formatTimeTwo,
  addDate
}